package com.heatup.apt.common.util.Netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException;

import java.util.List;

/**
 * Created by blank on 2017/11/16 下午6:01
 */
public class SafeByteToMessageDecoder extends ByteToMessageDecoder {//实现继承 ByteToMessageDecoder 来将字节解码为消息
    private static final int MAX_FRAME_SIZE = 1024;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {

        int readable = in.readableBytes();
        if (readable > MAX_FRAME_SIZE) {//检测缓冲区数据是否大于 MAX_FRAME_SIZE
            in.skipBytes(readable);//忽略所有可读的字节，并抛出 TooLongFrameException 来通知 ChannelPipeline 中的 ChannelHandler 这个帧数据超长
            throw new TooLongFrameException("Frame too big!");
        }
    }
}
